import {_decorator, director, instantiate, Node, Prefab, UITransform} from 'cc';
import {CircleManager} from "db://assets/Scripts/H2A/CircleManager";
import {RenderManager} from "db://assets/Scripts/Base/RenderManager";
import DataManager from "db://assets/Scripts/Runtime/DataManager";
import {SceneEnum, TriggerStatusEnum} from "db://assets/Scripts/Enum";

const {ccclass, property} = _decorator;


const CIRCLE_RADIUS = 80 // 圆半径

@ccclass('H2AGameManager')
export class H2AGameManager extends RenderManager {
    @property([CircleManager])
    circles: CircleManager[] = []

    @property(Node)
    lines: Node = null

    @property(Prefab)
    line: Prefab = null

    @property([Prefab])
    contentPrefab: Prefab[] = []

    // 每一个 circle 能通往哪些 circle 的映射
    private circleMap: Map<CircleManager, CircleManager[]> = new Map()

    start() {
        this.generateCircleMap()
        this.generateLines()
        super.start()
        this.checkSuccess() // 保险
    }

    render(): void {
        for (let i = 0; i < this.circles.length; i++) {
            const circle = this.circles[i]
            circle.node.destroyAllChildren()

            const contentIndex = DataManager.Instance.H2AData[i]
            if (contentIndex !== null && this.contentPrefab[contentIndex]) {
                const content = instantiate(this.contentPrefab[contentIndex])
                circle.node.addChild(content)
            }
        }
    }

    handleCircleTouch(e: Event, _index: string) {
        // 避免乱点
        if (DataManager.Instance.doorStatus === TriggerStatusEnum.Resolved) {
            return
        }

        const index = parseInt(_index)
        const curCircleContentIndex = DataManager.Instance.H2AData[index]
        if (curCircleContentIndex === null) {
            return
        }

        const curCircle = this.circles[index]
        const circles = this.circleMap.get(curCircle)
        for (let i = 0; i < circles.length; i++) {
            const circle = circles[i]

            const nullIndex = DataManager.Instance.H2AData.findIndex(i => i === null)
            const circleIndex = this.circles.findIndex(i => i === circle)

            if (nullIndex === circleIndex) { // 将点击棋子移动到空位置
                DataManager.Instance.H2AData[circle.index] = curCircleContentIndex
                DataManager.Instance.H2AData[index] = null
                DataManager.Instance.H2AData = [...DataManager.Instance.H2AData]
            }
        }

        this.checkSuccess()
    }

    checkSuccess() { // 小游戏成功之后设置门的状态以及跳转回 H2 场景
        const success = DataManager.Instance.H2AData.every(
            (e, i) => DataManager.Instance.H2AAnswer[i] === e
        )
        if (success) {
            DataManager.Instance.doorStatus = TriggerStatusEnum.Resolved
            // director.loadScene(SceneEnum.H2)
            DataManager.Instance.curScene = SceneEnum.H2
        }
    }

    resetContent() {
        DataManager.Instance.H2AData = [...DataManager.Instance.H2AInitData]
    }

    generateCircleMap() {
        const c = this.circles
        this.circleMap.set(c[0], [c[1], c[4], c[6]])
        this.circleMap.set(c[1], [c[0], c[5], c[6]])
        this.circleMap.set(c[2], [c[4], c[6]])
        this.circleMap.set(c[3], [c[5], c[6]])
        this.circleMap.set(c[4], [c[0], c[2], c[5], c[6]])
        this.circleMap.set(c[5], [c[1], c[3], c[4], c[6]])
        this.circleMap.set(c[6], [c[0], c[1], c[2], c[3], c[4], c[5]])

        for (let i = 0; i < this.circles.length; i++) {
            const circle = this.circles[i]
            circle.index = i
        }
    }

    generateLines() {
        for (const [curCircle, circles] of this.circleMap) {
            for (const nextCircle of circles) {
                const curIndex = this.circles.findIndex(i => i === curCircle)
                const nextIndex = this.circles.findIndex(i => i === nextCircle)
                // 线条虽然是双向的，但是只要画一次就好
                if (curIndex < nextIndex) {
                    this.generateLine(curCircle, nextCircle)
                }
            }
        }
    }

    private generateLine(curCircle: CircleManager, nextCircle: CircleManager) {
        const line = instantiate(this.line)

        // 设置线条位置
        const {x: x1, y: y1} = curCircle.node.position
        const {x: x2, y: y2} = nextCircle.node.position
        const x = (x1 + x2) / 2
        const y = (y1 + y2) / 2
        line.setPosition(x, y)

        // 设置线条长度
        const side1 = Math.abs(x1 - x2)
        const side2 = Math.abs(y1 - y2)
        const side3 = Math.sqrt(side1 ** 2 + side2 ** 2)
        const uiTransform = line.getComponent(UITransform)
        uiTransform.setContentSize(side3 - 2 * CIRCLE_RADIUS, uiTransform.height)

        // 设置旋转
        const rad = Math.atan(side2 / side1)
        const angle = rad * 180 / Math.PI
        const sign = (x1 > x2 && y1 > y2) || (x1 < x2 && y1 < y2) ? 1 : -1// 一三象限
        line.setRotationFromEuler(0, 0, sign * angle)

        this.lines.addChild(line)
    }
}
